import { getTagsList } from '@/services/creationCenter';
import { SaveArticleInfo } from '@/services/creationCenter/typing';
import { getToken } from '@/utils/operateToken';
import { RocketTwoTone } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  DrawerForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { Button, Form, Image, message } from 'antd';
import { UploadChangeParam } from 'antd/es/upload';
import { useEffect, useRef, useState } from 'react';
import type { FormInfo } from '../typing';

interface PublishFormProps {
  confirmPublish: (info: FormInfo) => void;
  initializeInfo: SaveArticleInfo;
}

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const PublishForm: React.FC<PublishFormProps> = ({
  confirmPublish,
  initializeInfo,
}) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    form.setFieldsValue({
      title: initializeInfo.title,
      type: initializeInfo.type,
      tags: initializeInfo.tags,
      coverImgList: initializeInfo.cover_img_url
        ? [
            {
              name: initializeInfo.cover_img_url.split('/').pop(),
              status: 'done',
              url: initializeInfo.cover_img_url,
            },
          ]
        : [],
      synopsis: initializeInfo.synopsis,
      original: initializeInfo.original,
    });
  }, [initializeInfo]);

  const [form] = Form.useForm<FormInfo>();
  // 获取标签列表
  async function getTags() {
    const { data } = await getTagsList();
    const tagColumn = data.list.map((tag) => ({
      label: tag.tag_name,
      value: tag.tag_id,
    }));
    return tagColumn;
  }

  // 上传图片
  function uploadImg(info: UploadChangeParam) {
    const { file } = info;
    if (info.file.status === 'error') {
      message.error('上传失败');
    }
    if (file.status === 'done') {
      const { code, data } = file.response;
      if (code === 0 && data) {
        formRef.current?.setFieldsValue({
          coverImgList: [
            {
              name: data.fileName,
              status: 'done',
              url: data.img_url,
            },
          ],
        });
        message.success('上传成功');
      }
    }
  }

  // 预览图片
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  function randomImg() {
    formRef.current?.setFieldsValue({
      coverImgList: [
        {
          name: '随机图片',
          status: 'done',
          url: process.env.RANDOM_COVER_IMG,
        },
      ],
    });
  }

  return (
    <div>
      <DrawerForm
        formRef={formRef}
        title="发布"
        resize={{
          onResize() {
            console.log('resize!');
          },
          maxWidth: window.innerWidth * 0.5,
          minWidth: 400,
        }}
        trigger={
          <Button color="primary" variant="solid" size="large">
            <RocketTwoTone twoToneColor="#fa1b95" />
            发布 文章/随记
          </Button>
        }
        drawerProps={{
          destroyOnClose: false, // 关闭时销毁 Drawer 里的子元素
        }}
        onFinish={async (info: FormInfo) => {
          confirmPublish(info);
          return true;
        }}
        form={form}
        autoFocusFirstInput
        submitTimeout={2000}
      >
        <ProFormText
          name="title"
          width="md"
          label="标题"
          tooltip="请在页面中修改"
          initialValue={initializeInfo.title}
          disabled
          rules={[
            {
              required: true,
            },
          ]}
        ></ProFormText>
        <ProFormRadio.Group
          name="type"
          label="类型"
          radioType="button"
          rules={[
            {
              required: true,
              message: '选择发布类型',
              type: 'enum',
              enum: [1, 2],
            },
          ]}
          options={[
            {
              value: 1,
              label: '文章',
            },
            {
              value: 2,
              label: '随记',
            },
          ]}
        />

        <ProFormRadio.Group
          name="original"
          label="是否原创"
          radioType="button"
          rules={[
            {
              required: true,
              message: '请选择',
            },
          ]}
          options={[
            {
              value: 0,
              label: '原创',
            },
            {
              value: 1,
              label: '转载',
            },
          ]}
        />

        <ProFormSelect
          name="tags"
          label="标签"
          request={getTags}
          fieldProps={{
            mode: 'multiple',
          }}
          width="md"
          placeholder="添加标签"
          rules={[
            {
              type: 'array',
              max: 3,
              message: '最多只能选择3个标签',
            },
          ]}
        />

        <ProFormUploadButton
          name="coverImgList"
          label="封面"
          title="上传封面"
          max={1}
          fieldProps={{
            name: 'file',
            listType: 'picture-card',
            headers: {
              Authorization: 'Bearer ' + getToken() || '',
            },
            onPreview: handlePreview,
          }}
          action="/api/file-manage"
          accept=".png,.jpg,jpeg"
          onChange={uploadImg}
          extra=<Button type="link" onClick={randomImg}>
            随机图片
          </Button>
        />
        <ProFormTextArea
          tooltip="100字以内"
          name="synopsis"
          label="摘要"
          placeholder="摘要"
          allowClear
          rules={[
            {
              message: '字数不能超过100',
              type: 'string',
              max: 100,
            },
          ]}
        />
      </DrawerForm>

      {previewImage && (
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
            afterOpenChange: (visible) => !visible && setPreviewImage(''),
          }}
          src={previewImage}
        />
      )}
    </div>
  );
};

export default PublishForm;
